import { setStorage } from '../utils/auth'
const actions = {}
const state = {
  cartList: [],
}
const mutations = {
  // 初始化购物车数据
  initCartList(state, cartList) {
    state.cartList = cartList
  },
  // 改变商品的选中状态
  changeCheck(state, goods) {
    const g = state.cartList.find(item => item.id === goods.id)
    g.isCheck = !g.isCheck
    // 将数据持久化
    setStorage('cartList', state.cartList)
  },
  // 点击全选
  allCheck(state) {
    const isAllCheck = state.cartList.every(item => item.isCheck === true)
    state.cartList.forEach(item => (item.isCheck = !isAllCheck))
    setStorage('cartList', state.cartList)
  },
  // 改变商品的规格
  changeSpec(state, { spec, goods }) {
    const g = state.cartList.find(item => item.id === goods.id)
    g.selectItem = spec
    setStorage('cartList', state.cartList)
  },
  // 改变商品的数量
  changeNum(state, { num, goods }) {
    const g = state.cartList.find(item => item.id === goods.id)
    g.num = num
    setStorage('cartList', state.cartList)
  },
}
const getters = {
  // 是否全选
  isAllCheck(state) {
    return (
      state.cartList.every(item => item.isCheck === true) &&
      state.cartList.length
    )
  },
  // 总价
  totalPrice(state) {
    let totalPrice = 0
    state.cartList.forEach(item => {
      if (item.isCheck) {
        totalPrice += parseFloat(item.selectItem.price) * Number(item.num)
      }
    })
    return totalPrice
  },
}

export default { namespaced: true, actions, state, mutations, getters }
